<template>
	<view>
		请站上设备
		<view class="devices_summary">当前状态：{{stateString}}</view>
		<view class="devices_summary" v-if="!connected">已发现 {{devices.length}} 个外围设备：</view>
		<scroll-view class="device_list" scroll-y scroll-with-animation v-if="!connected">
			<view class="popup-box">
				<scroll-view scroll-y="true" style="height: 350upx;">
					<view class="facility-bg" v-for="(item,idx) in devices" :key="idx">
						<view class="bluetooth"></view>
						<view style="width: 420upx;">体脂秤</view>
						<button class="facility-btn" @tap="tbEquipmentUser(item,idx)" type="default">立即绑定</button>
					</view>
				</scroll-view>
			</view>
		</scroll-view>
		<view class="connected_info" v-if="connected">
			<view>
				<text>{{device.mac}} </text>
				<text style="font-size:20px">重量: {{weight}}</text>
				<view class="operation">
					<button size="mini" bindtap="closeBLEConnection">断开连接</button>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	// #ifdef MP-WEIXIN
	const QNBleApi = require("@/components/peripheral/qnble")
	import { init } from '@/sg/index'
	// #endif
	export default {
		data() {
			return {
				age: 30,
				autoStopDiscovery: true,
				gender: "male",
				height: 170,
				isSport: true,
				unit: "kg",
				devices: [],
				connected: false,
				stateString: "空闲",
				weight: 0,
				device: {}
			}
		},
		created() {
			let options = {};
			//蓝牙初始化
			options.form =
				'{"measureMethod":"auto","gender":"male","height":170,"age":30,"isSport":false,"unit":"kg","autoStopDiscovery":true}'
			if (options.form) {
				const form = JSON.parse(options.form)
				this.age = form.age;
				this.autoStopDiscovery = form.autoStopDiscovery;
				this.gender = form.gender;
				this.height = form.height;
				this.isSport = form.isSport;
				this.measureMethod = form.measureMethod;
				this.unit = form.unit;
			}
			this.bleApi = new QNBleApi()

			this.bleApi.setDeviceEventListener(this);
			this.bleApi.setBleEventListener(this);
			wx.openBluetoothAdapter({
				mode: "peripheral",
				success: res => {
					wx.createBLEPeripheralServer({
						success: res => {
							//设置广播秤的蓝牙服务
							console.log("设置蓝牙服务")
							this.bleApi.setBleServer(res.server)
						}
					})
				}
			})
			console.log(111, '84')
		},
		mounted() {
			this.bleApi.init({
				appId: "wx3581a642cd0e4a4d",
				secret: "42e4c5d4a8d52e5241b29022a7b9865c",
				logger: this.logger(),
			});
			console.log(222, '92')
			// this.testRequest()
			setTimeout(() => {
				this.openBluetoothAdapter()
			}, 500);
		},
		// 组件加载完毕
		updated() {
			// 调用搜索设备
		},
		destroyed() {
			this.bleApi.stop()
			init(global.userInfo.userId)
		},
		methods: {

			//下面是点击事件
			tbEquipmentUser() {
				this.$emit('equipment', this.device)
			},
			// 开始扫描
			openBluetoothAdapter() {
				this.bleApi.startBleDeviceDiscovery();
			},

			stopBluetoothDevicesDiscovery() {
				this.bleApi.stopBleDeviceDiscovery();
			},

			closeBluetoothAdapter() {
				this.bleApi.stop()
			},
			createBLEConnection(event) {
				const mac = event.currentTarget.dataset.mac;
				const idx = this.inArray(this.devices, "mac", mac);
				const device = this.devices[idx];
				const {
					height,
					age,
					gender,
					isSport,
					unit
				} = this
				const birthday = new Date()
				birthday.setFullYear(birthday.getFullYear() - age)
				const user = {
					height,
					age,
					gender,
					isSport,
					birthday,
				}
				this.bleApi.createBleConnection(device, {
					user,
					unit
				})
			},
			closeBLEConnection() {
				this.bleApi.closeBleConnection()
			},
			updateState(state) {
				this.stateString = state
			},

			//下面是蓝牙事件的相关回调
			//开始扫描的回调
			onInitSuccess(bleEnableState) {
				if (bleEnableState) {
					this.updateState("蓝牙可用")
				} else {
					this.updateState("蓝牙不可用")
				}
			},
			onStartDiscoveryDevice() {
				this.updateState("开始扫描")
				this.devices = []
			},

			//结束扫描的回到
			onStopDiscoveryDevice() {
				this.updateState("已停止扫描")
			},
			//回调扫描对象
			onBleDeviceFound(device) {
				console.log("出现设备", device);
				this.device = device;
				const foundDevices = this.devices;
				const idx = this.inArray(foundDevices, "mac", device.mac);
				const data = {};
				console.log(foundDevices, idx, data, 169)
				if (idx === -1) {
					// data[`devices[${foundDevices.length}]`] = device;
					this.$set(this.devices, foundDevices.length, device);
				} else {
					this.$set(this.devices, idx, device);
					// data[`devices[${idx}]`] = device;
				}
				// console.log(data,173)
				// this.devices = data;
				// this.connected = true
				// this.setData(data);
				// this.bleApi.stopBleDeviceDiscovery(this)
				// this.bleApi.connectDevice(device)
			},
			/**
			 * 正在进行连接设备，在调用连接设备后，会马上回调
			 */
			onConnecting(device) {
				this.updateState("正在连接")
				this.connected = false
			},
			/**
			 * 	设备已连接成功 会回调设备对象
			 */
			onConnected(device) {
				this.updateState("已连接")
				console.log("设备已连接", device);
				this.connected = true
				this.device = device
			},
			onBluetoothEnableChange(bleEnableStatus) {
				if (bleEnableStatus) {
					this.updateState("蓝牙可用，空闲")
					wx.openBluetoothAdapter({
						mode: "peripheral",
						success: res => {
							wx.createBLEPeripheralServer({
								success: res => {
									//设置广播秤的蓝牙服务
									console.log("设置蓝牙服务")
									this.bleApi.setBleServer(res.server)
								}
							})
						}
					})
				} else {
					this.updateState("蓝牙不可用")
				}
			},


			/**
			 * 	设备的服务搜索完成，正常情况下会在 onConnected后面调用
			 */
			onDeviceReady(device) {
				this.updateState("设备已经就绪")
				console.log("设备已就绪", device);
			},

			/**
			 * 蓝牙断开了连接
			 */
			onDisconnected(device) {
				this.updateState("设备连接已断开")
				this.connected = false
				console.log("设备连接已断开", device);
			},

			//下面是秤端相关事件回调
			onGetUnsteadyWeight(weight) {
				console.log("收到不稳定重量", weight);
				this.weight = weight
				// this.weight
			},
			/**
			 * 获取到了实时的稳定测量数据，在连接APP的情况下，进行测量，数据会进入到这个回调
			 * @param {object} scaleData 体脂秤数据
			 */
			onGetScaleData(scaleData) {
				this.updateState("测量完成")
				console.log("收到最终数据", scaleData);
				this.weight = scaleData.weight
			},

			testRequest() {
				var d = new Date();
				d.setFullYear(1990)
				var user = {
					height: 170,
					gender: 1,
					birthday: d,

				}
				this.bleApi.setOperation({
					action: "measuring",
					user,
					unit: "kg",
				})

				this.bleApi.fakeRequest()

			},

			inArray: (arr, key, val) => {
				for (let i = 0; i < arr.length; i++) {
					// console.log("数组查找", arr[i], arr[i][key], val);

					if (typeof val == "undefined") {
						throw "错误的比较对象";
					}

					if (arr[i][key] === val) {
						return i;
					}
				}
				return -1;
			},
			logger: () => {
				const wxlogger = wx.getLogManager && wx.getLogManager({
					level: 0,
				})
				const log = (...params) => {
					console.log(...params)
					wxlogger && wxlogger.log(...params)
				}
				return {
					log
				}
			},
		}
	}
</script>

<style>
	
</style>
